import { getFromStorage, saveToStorage } from "./storage.js"

export async function getSettings() {
  const defaults = {
    theme: "system",
    accentColor: "#4f46e5",
    // language: chrome.i18n.getUILanguage?.().startsWith("zh") ? "zh" : "en",
    encryptSensitive: false
  }
  const data = await getFromStorage("settings")
  return { ...defaults, ...(data || {}) }
}

export async function setSettings(partial) {
  const prev = await getSettings()
  const next = { ...prev, ...partial }
  await saveToStorage("settings", next)
}

export function applyTheme(theme, accent) {
  const isLight =
    theme === "light" ||
    (theme === "system" &&
      window.matchMedia("(prefers-color-scheme: light)").matches)
  document.documentElement.classList.toggle("theme-light", isLight)
  document.documentElement.style.setProperty("--accent", accent || "#4f46e5")
}

export async function populateLanguageSelect(selectEl, current) {
  const languages = [
    { code: "en", label: "English" },
    { code: "zh", label: "简体中文" }
  ]
  selectEl.innerHTML = ""
  for (const lang of languages) {
    const opt = document.createElement("option")
    opt.value = lang.code
    opt.textContent = lang.label
    if (lang.code === current) opt.selected = true
    selectEl.appendChild(opt)
  }
}

export function t(key) {
  try {
    return chrome.i18n.getMessage(key) || key
  } catch (_e) {
    return key
  }
}

export function loadSettingIntoDOM() {
  /* reserved */
}
